package com.quanshu.exchange.ui.gui.profile;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.ShopInterface;
import com.quanshu.exchange.support.entity.AddressEntity;
import com.quanshu.exchange.support.entity.tmp.AreaData;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.LogUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.sevenheaven.iosswitch.ShSwitchView;

import org.json.JSONArray;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 新增地址
 * Created by xiniu003 on 2018/1/2.
 */

public class AddDelivryAddressActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.delivery_name)
    EditText deliveryName;
    @BindView(R.id.delivery_phone)
    EditText deliveryPhone;
    @BindView(R.id.delivery_address_province)
    TextView deliveryAddressProvince;
    @BindView(R.id.delivery_address_details)
    EditText deliveryAddressDetails;
    @BindView(R.id.delivery_default)
    ShSwitchView deliveryDefault;
    @BindView(R.id.delivery_address_add_enter)
    LinearLayout deliveryAddressAddEnter;

    private ArrayList<AreaData> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<AreaData>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<AreaData>>> options3Items = new ArrayList<>();
    private OptionsPickerView pickerView;

    private String str_area;//所在地区--
    private String deliveryNameStr;//收货人 - 姓名
    private String deliveryPhoneStr;//收货人 - 手机号
    private String deliveryAddressProvinceStr;//所在地区
    private String deliveryAddressDetailsStr;//详细地址
    private int deliveryIsDefault;//是否为默认地址

    boolean addGroupCheck = false;

    private String typeStr;//新增，修改 - 标识

    private int province_id;
    private int city_id;
    private int area_id;

    private AddressEntity addressEntity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delivery_address_add);
        ButterKnife.bind(this);
        getIntentData();
        initListener();
    }

    private void getIntentData() {
        Intent intent = getIntent();
        typeStr = intent.getStringExtra("add");
        if (typeStr.equals("新增")) {

        }
        if (typeStr.equals("修改")) {
            addressEntity = (AddressEntity) intent.getSerializableExtra("AddressEntity");

            deliveryName.setText(addressEntity.getAccept_name());
            deliveryPhone.setText(addressEntity.getMobile());
            deliveryAddressProvince.setText(
                    addressEntity.getProvince_val() +
                            addressEntity.getCity_val() +
                            addressEntity.getArea_val());
            deliveryAddressDetails.setText(addressEntity.getAddress());

            deliveryAddressProvinceStr = addressEntity.getProvince_val() +
                    addressEntity.getCity_val() +
                    addressEntity.getArea_val();
            province_id = Integer.parseInt(addressEntity.getProvince());
            city_id = Integer.parseInt(addressEntity.getCity());
            area_id = Integer.parseInt(addressEntity.getArea());
            deliveryIsDefault = Integer.parseInt(addressEntity.getIs_default());

            addGroupCheck = deliveryDefault.isOn();
            if (deliveryIsDefault == 1) {
                addGroupCheck = true;
            } else if (deliveryIsDefault == 0) {
                addGroupCheck = false;
            }
        }

    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> finish());

        RxViewHelper.getInstance().afterTextChangeEvents(deliveryName,
                textViewAfterTextChangeEvent -> {
                    deliveryNameStr = textViewAfterTextChangeEvent.editable().toString();
                });

        RxViewHelper.getInstance().afterTextChangeEvents(deliveryPhone,
                textViewAfterTextChangeEvent -> {
                    deliveryPhoneStr = textViewAfterTextChangeEvent.editable().toString();
                });

        RxViewHelper.getInstance().clicks(deliveryAddressProvince, aVoid -> doPickArea());

        RxViewHelper.getInstance().afterTextChangeEvents(deliveryAddressDetails,
                textViewAfterTextChangeEvent -> {
                    deliveryAddressDetailsStr = textViewAfterTextChangeEvent.editable().toString();
                });

        setSwitch();

        RxViewHelper.getInstance().clicks(deliveryAddressAddEnter, aVoid -> doSaveAddressEnter());
    }

    private void doSaveAddressEnter() {
        if (TextUtils.isEmpty(deliveryNameStr)) {
            ToastHelper.toast("您还未输入收货人姓名");
            return;
        }

        if (TextUtils.isEmpty(deliveryPhoneStr)) {
            ToastHelper.toast("您还未输入收货人手机号");
            return;
        }

        if (TextUtils.isEmpty(deliveryAddressProvinceStr)) {
            ToastHelper.toast("您还未选择所在地区");
            return;
        }

        if (TextUtils.isEmpty(deliveryAddressDetailsStr)) {
            ToastHelper.toast("您还未输入详细地址");
            return;
        }

//        ToastHelper.toast("可以");

        if (typeStr.equals("新增")) {
            getInsertAddr();
        }

        if (typeStr.equals("修改")) {

            if (deliveryNameStr.equals(addressEntity.getAccept_name()) &&
                    deliveryPhoneStr.equals(addressEntity.getMobile()) &&
                    deliveryAddressProvinceStr.equals(addressEntity.getProvince_val() +
                            addressEntity.getCity_val() +
                            addressEntity.getArea_val()) &&
                    deliveryAddressDetailsStr.equals(addressEntity.getAddress()) &&
                    deliveryIsDefault == Integer.valueOf(addressEntity.getIs_default())) {
                ToastHelper.toast("您未作出修改！");
            } else {
                getEditAddr();
            }
        }


    }


    private void setSwitch() {
        deliveryDefault.setOnSwitchStateChangeListener(isOn -> {
            addGroupCheck = deliveryDefault.isOn();
            if (addGroupCheck == true) {
                deliveryIsDefault = 1;
            } else {
                deliveryIsDefault = 0;
            }
        });
    }

    //修改收货地址
    private void getEditAddr() {
        NetClient.getInstance()
                .getShopService(ShopInterface.class)
                .getEditAddr(AppUtils.getSignParams(String.valueOf(currentUser.getId()),
                        addressEntity.getId(),
                        deliveryNameStr,
                        deliveryPhoneStr,
                        province_id + "",
                        city_id + "",
                        area_id + "",
                        deliveryAddressDetailsStr,
                        deliveryIsDefault + ""), String.valueOf(currentUser.getId()),
                        addressEntity.getId(),
                        deliveryNameStr,
                        deliveryPhoneStr,
                        province_id,
                        city_id,
                        area_id,
                        deliveryAddressDetailsStr,
                        deliveryIsDefault)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        ToastHelper.toast(response.getMsg());
                        Intent intent = getIntent();
                        setResult(RESULT_OK, intent);
                        finish();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        super.onFailure(e);
                    }
                });
    }

    //新增收货地址
    private void getInsertAddr() {
        NetClient.getInstance()
                .getShopService(ShopInterface.class)
                .getInsertAddr(AppUtils.getSignParams(String.valueOf(currentUser.getId()),
                        deliveryNameStr,
                        deliveryPhoneStr,
                        province_id + "",
                        city_id + "",
                        area_id + "",
                        deliveryAddressDetailsStr,
                        deliveryIsDefault + ""), String.valueOf(currentUser.getId()),
                        deliveryNameStr,
                        deliveryPhoneStr,
                        province_id,
                        city_id,
                        area_id,
                        deliveryAddressDetailsStr,
                        deliveryIsDefault)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        ToastHelper.toast(response.getMsg());
                        Intent intent = getIntent();
                        setResult(RESULT_OK, intent);
                        finish();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        LogUtil.printException(e);
                    }
                });
    }

    private void doPickArea() {

        if (pickerView == null) {
            pickerView = new OptionsPickerView.Builder(this, (options1, options2, options3, v) -> {
                //返回的分别是三个级别的选中位置
                str_area = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2).getPickerViewText() +
                        options3Items.get(options1).get(options2).get(options3).getPickerViewText();

                province_id = Integer.parseInt(options1Items.get(options1).getArea_id());//省编码
                city_id = Integer.parseInt(options2Items.get(options1).
                        get(options2).
                        getArea_id());//市编码
                area_id = Integer.parseInt(options3Items.get(options1).
                        get(options2).
                        get(options3).
                        getArea_id());//区编码


                deliveryAddressProvince.setText(str_area);
                deliveryAddressProvinceStr = str_area;
            })
                    .setTitleBgColor(Color.parseColor("#FFFFFF"))
                    .setCancelText("")
                    .setCancelColor(Color.parseColor("#FFF9E3"))
                    .setSubmitColor(Color.parseColor("#333333"))
                    .setBgColor(Color.parseColor("#FFFFFF"))
                    .setDividerColor(Color.parseColor("#C4C4C4"))
                    .setTextColorCenter(Color.parseColor("#333333")) //设置选中项文字颜色
                    .setContentTextSize(18)
                    .setSubCalSize(16)
                    .build();
        }
        if (options1Items.size() < 1 || options2Items.size() < 1 || options3Items.size() < 1) {
            initJsonData();
        }
        pickerView.setPicker(options1Items, options2Items, options3Items);
        pickerView.show();
    }

    private void initJsonData() {//解析数据

        String JsonData = AppUtils.getJson(this, "area.json");//获取assets目录下的json文件数据
        ArrayList<AreaData> jsonBean = parseData(JsonData);//用Gson 转成实体

        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<AreaData> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<AreaData>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            if (jsonBean.get(i).getArea_list() != null && jsonBean.get(i).getArea_list().size() > 0) {
                for (int c = 0; c < jsonBean.get(i).getArea_list().size(); c++) {//遍历该省份的所有城市
                    CityList.add(jsonBean.get(i).getArea_list().get(c));//添加城市
                    ArrayList<AreaData> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                    //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                    if (jsonBean.get(i).getArea_list().get(c).getArea_list() != null &&
                            jsonBean.get(i).getArea_list().get(c).getArea_list().size() > 0) {
                        for (int d = 0;
                             d < jsonBean.get(i).getArea_list().get(c).getArea_list().size();
                             d++) {//该城市对应地区所有数据
                            City_AreaList.add(jsonBean.
                                    get(i).getArea_list().
                                    get(c).getArea_list().get(d));//添加该城市所有地区数据
                        }
                    }
                    Province_AreaList.add(City_AreaList);//添加该省所有地区数据
                }
            }
            //  添加城市数据
            options2Items.add(CityList);
            // 添加地区数据
            options3Items.add(Province_AreaList);
        }
    }

    public ArrayList<AreaData> parseData(String result) {//Gson 解析
        ArrayList<AreaData> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                AreaData entity = gson.fromJson(data.optJSONObject(i).toString(), AreaData.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }
}
